<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>#define</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C/C++ Pre-processor Commands</a> &gt; <a href=
    "define.html">#define</a>
  </div>

  <div class="name-format">
    #define
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #define macro-name replacement-string
</pre>

  <p>The #define command is used to make substitutions throughout the
  file in which it is located. In other words, #define causes the
  compiler to go through the file, replacing every occurrence of
  <em>macro-name</em> with <em>replacement-string</em>. The replacement
  string stops at the end of the line.</p>

  <div class="related-examples-format">
    Example code:
  </div>

  <div class="related-examples">
    <p>Here&#39;s a typical use for a #define (at least in C):</p>
    <pre class="example-code">
   #define TRUE 1
   #define FALSE 0
   ...
   int done = 0;
   while( done != TRUE ) {
      ...
   }            
</pre>

    <p>Another feature of the #define command is that it can take
    arguments, making it rather useful as a pseudo-function creator.
    Consider the following code:</p>
    <pre class="example-code">
   #define absolute_value( x ) ( ((x) &lt; 0) ? -(x) : (x) )
   ...
   int x = -1;
   while( absolute_value( x ) ) {
      ...
   }            
</pre>

    <p>It&#39;s generally a good idea to use extra parentheses when
    using complex macros. Notice that in the above example, the
    variable &quot;x&quot; is always within it&#39;s own set of
    parentheses. This way, it will be evaluated in whole, before being
    compared to 0 or multiplied by -1. Also, the entire macro is
    surrounded by parentheses, to prevent it from being contaminated by
    other code. If you&#39;re not careful, you run the risk of having
    the compiler misinterpret your code.</p>

    <p>Here is an example of how to use the #define command to create a
    general purpose incrementing for loop that prints out the integers
    1 through 20:</p>
    <pre class="example-code">
 #define count_up( v, low, high ) \
   for( (v) = (low); (v) &lt;= (high); (v)++ )          

 ...            

 int i;
 count_up( i, 1, 20 ) {
   printf( &quot;i is %d\n&quot;, i );
 }              
</pre>
  </div>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="sharp.html">#, ##</a><br>
    <a href="preprocessor_if.html">#if, #ifdef, #ifndef, #else, #elif,
    #endif</a><br>
    <a href="undef.html">#undef</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
